from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import logging, datetime, jwt, json, base64, re, hashlib, hmac, time
from django.utils import timezone
from django.conf import settings
from rest_framework.viewsets import ModelViewSet
from random import randint, Random, uniform, shuffle
import Crypto.Signature.PKCS1_v1_5 as sign_PKCS1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from django.db import transaction
import uuid
from django.db.models.expressions import RawSQL
from django.db.models import Q, F
from django.shortcuts import render
from django.http.response import HttpResponse

from vouchers.utils import AlipayOpen
from vouchers.serializers import *
from equity_mall.utils.pages import MyPage
from equity_mall.utils.utils import random_str
from users.models import User
from customers.utils import AlipayOpen as c_AlipayOpen, pay_transactions_jsapi, pay_transactions_native, favor_distributed_coupons, favor_query_coupons
from orders.models import APIWhiteTable
from vouchers.tasks import *
from equity_mall.utils.wash_level1 import encrypt, get_sign, decrypt, haizhui_get_sign
from postallive.models import *
from merchants.models import Merchant
from customers.serializers import MerchantListModelSerializer
from equity_admin.utils import get_stockinfo
from activities.models import Channel

logger = logging.getLogger('django')
logger_vouchers = logging.getLogger('vouchers')


class UserLoginView(APIView):
    '''游客登录'''

    permission_classes = ()

    def post(self, request):
        code = self.request.data.get('code', None)
        if not code:
            return Response({'error': '缺少必传参数!'}, status=status.HTTP_400_BAD_REQUEST)
        alipay_obj = AlipayOpen()
        result = json.loads(alipay_obj.systemoauthtoken(code))
        if 'user_id' not in result:
            return Response({'error': '获取用户信息失败,请重新扫码'}, status=status.HTTP_400_BAD_REQUEST)
        user_id = result['user_id']
        user = AliAuthUser.objects.filter(user_id=user_id).first()
        if not user:
            user, create = AliAuthUser.objects.get_or_create(defaults={'user_id': user_id}, user_id=user_id)
        # user = AliAuthUser.objects.get(id=1)
        # user_id = user.user_id
        dic = {
            'exp': timezone.now() + datetime.timedelta(days=30),
            'iat': timezone.now(),
            'iss': 'xinheng',
            'data': {
                'user_id': user_id,
                'id': user.id
            },
        }
        jwt_token = jwt.encode(dic, settings.SECRET_KEY1, algorithm='HS256')
        return Response({
            'user_id': user.user_id,
            'token': jwt_token
        }, status=status.HTTP_200_OK)


class AliFlipCARDSModelViewSet(ModelViewSet):

    pagination_class = MyPage

    def get_serializer_class(self):
        if self.action == 'list':
            return AliFlipCARDSListModelSerializer
        else:
            return AliFlipCARDSListModelSerializer

    def get_queryset(self):
        user = self.request.iser
        activity_identify = self.request.query_params.get('activity_identify', None)
        if self.action == 'list':
            if activity_identify:
                queryset = AliFlipCARDS.objects.filter(aliuser=user, open_status__in=[2, 4], aliactivity__identify=activity_identify)
            else:
                queryset = AliFlipCARDS.objects.filter(aliuser=user, open_status__in=[2, 4])
        else:
            queryset = AliFlipCARDS.objects.filter(aliuser=user)
        return queryset

    def update(self, request, *args, **kwargs):
        user = self.request.iser
        instance = self.get_object()
        if instance.open_status != 1:
            return Response({'error': '礼包状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        ali_activity = instance.aliactivity
        if ali_activity.lucky_count == AliFlipCARDS.objects.filter(aliuser=user, aliactivity=ali_activity).exclude(open_status=1).count():
            return Response({'error': '已达到抽奖上限'}, status=status.HTTP_400_BAD_REQUEST)
        data = {}
        if instance.win_type != 3:
            instance.open_status = 2
            instance.open_time = datetime.datetime.now()
            instance.save()
            if instance.win_type == 2:
                data['amount'] = instance.amount
                data['msg'] = ''
                data['win_type'] = 2
            else:
                data['amount'] = instance.alidiscountcoupon.amount
                data['msg'] = instance.alidiscountcoupon.floor_amount
                data['win_type'] = 1
            return Response({'success': '恭喜你中奖了', 'data': data}, status=status.HTTP_200_OK)
        else:
            instance.open_status = 3
            instance.open_time = datetime.datetime.now()
            instance.save()
            data['amount'] = ''
            data['msg'] = ''
            data['win_type'] = 3
            return Response({'success': '谢谢参与', 'data': data},status=status.HTTP_200_OK)

    def partial_update(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.open_status != 2:
            return Response({'error': '礼包状态有误'}, status=status.HTTP_400_BAD_REQUEST)
        alipay_obj = AlipayOpen()
        user = self.request.iser
        user_id = user.user_id
        if instance.win_type == 1:
            alidiscountcoupon = instance.alidiscountcoupon
            out_biz_no = instance.identify
            template_id = alidiscountcoupon.template_id
            result = json.loads(alipay_obj.vouchersend(user_id, template_id, out_biz_no))
            if result['code'] != '10000':
                print(result)
                return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            voucher_id = result['voucher_id']
            result = json.loads(alipay_obj.voucherquery(voucher_id))
            data = {
                'alidiscountcoupon_id': alidiscountcoupon.id,
                'voucher_id': voucher_id,
                'user_id': user_id,
                'template_id': result['template_id'],
                'gmt_active': result['gmt_active'],
                'gmt_expired': result['gmt_expired'],
                'total_amount': result['total_amount'],
                'gmt_create': result['gmt_create'],
                'available_amount': result['available_amount'],
                'name': result['name'],
                'out_biz_no': out_biz_no,
                'aliuser_id': user.id,
                'aliflipcards_id': instance.id,
                'coupon_channel': alidiscountcoupon.coupon_channel
            }
            alidiscountcoupon.send_count += 1
            alidiscountcoupon.save()
            instance.open_status = 4
            instance.save()
            voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
            if create:
                return Response({'success': '领取成功'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            out_biz_no = instance.identify
            order_title = '邮储银行消费红包'
            trans_amount = instance.amount
            result = json.loads(alipay_obj.transunitransfer(user_id, out_biz_no, trans_amount, order_title))
            if result['code'] != '10000':
                return Response({'error': '领取失败,请联系管理员'}, status=status.HTTP_400_BAD_REQUEST)
            data = {
                'trans_date': result['trans_date'],
                'order_id': result['order_id'],
                'out_biz_no': out_biz_no,
                'order_title': order_title,
                'aliuser_id': user.id,
                'aliflipcards_id': instance.id,
                'trans_amount': instance.amount
            }
            if 'pay_fund_order_id' in result:
                data['pay_fund_order_id'] = result['pay_fund_order_id']
            alifundtransfer, create = AliFundTransfer.objects.get_or_create(defaults=data, order_id=result['order_id'])
            instance.open_status = 4
            instance.save()
            if create:
                return Response({'success': '领取成功'}, status=status.HTTP_200_OK)
            else:
                return Response({'error': '已经领取过了'}, status=status.HTTP_400_BAD_REQUEST)

    def flip_panel(self, request):
        activity_identify = self.request.query_params.get('activity_identify', None)
        if not activity_identify:
            return Response({'error': '缺少必传参数'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            ali_activity = AliActivity.objects.get(identify=activity_identify)
        except:
            return Response({'error': '活动不存在,或者活动已经结束'}, status=status.HTTP_400_BAD_REQUEST)
        if ali_activity.activity_state == 1:
            return Response({'error': '活动尚未开始,敬请期待'}, status=status.HTTP_400_BAD_REQUEST)
        if ali_activity.activity_state != 2:
            return Response({'error': '活动已经结束,敬请期待下一次活动'}, status=status.HTTP_400_BAD_REQUEST)
        user = self.request.iser
        queryset = AliFlipCARDS.objects.filter(aliuser=user, aliactivity=ali_activity)
        if not queryset:
            x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
            aliactivityrules_set = ali_activity.aliactivityrules_set.all()
            shuffle(x)
            randint_choices = {
                1: False,
                2: False,
                3: False,
                4: False,
                5: False,
                6: False,
                7: False,
                8: False,
                9: False
            }
            a = 1
            for aliactivityrules in aliactivityrules_set:
                for i in range(a, a+aliactivityrules.count):
                    randint_choices[i] = aliactivityrules
                a += aliactivityrules.count
            for i in x:
                identify = f'100002{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                data = dict()
                data['identify'] = identify
                data['aliuser_id'] = user.id
                data['gears'] = i
                if randint_choices[i]:
                    if randint_choices[i].rule_type == 1:
                        data['alidiscountcoupon_id'] = randint_choices[i].alidiscountcoupon_id
                        data['win_type'] = 1
                    else:
                        data['amount'] = randint(int(randint_choices[i].amount_min*100), int(randint_choices[i].amount_max*100)) / 100
                        data['win_type'] = 2
                AliFlipCARDS.objects.get_or_create(defaults=data, gears=i, aliuser_id=user.id, aliactivity_id=ali_activity.id)
            queryset = AliFlipCARDS.objects.filter(aliuser=user, aliactivity=ali_activity)
        data = {}
        data['lists'] = AliFlipCARDSListModelSerializer(queryset, many=True).data
        data['count'] = ali_activity.lucky_count - queryset.exclude(open_status__in=[1, 5]).count()
        return Response(data, status=status.HTTP_200_OK)


class AliDiscountCouponInfoModelViewSet(ModelViewSet):

    pagination_class = MyPage
    serializer_class = MerchantListModelSerializer

    def payout(self, request):
        headers = request.META.get('HTTP_AUTHORIZATION')
        data = self.request.data
        activity_id = data.get('activity_id', None)
        login_id = data.get('login_id', None)
        mobile = data.get('mobile', None)
        try:
            header_list = headers.split(',')
        except:
            return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        header_dic = {}
        for header in header_list:
            if header:
                try:
                    header = header.split('=')
                    header_dic[header[0]] = header[1]
                except:
                    return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if ('company' and 'timestamp' and 'nonce_str' and 'signature') not in header_dic:
            return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '活动参数必传', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not login_id:
            return Response({'code': 400, 'message': '支付宝账号参数必传', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(account=header_dic['company'], is_active=1)
        except:
            return Response({'code': 400, 'message': '无效接入方标识', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not user.is_developer:
            return Response({'code': 400, 'message': '用户尚未开通权限', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        message = f'POST\n/voucher/payout/\n{header_dic["timestamp"]}\n{header_dic["nonce_str"]}\n{json.dumps(data, ensure_ascii=False)}\n'
        message1 = f'POST\n/voucher/payout/\n{header_dic["timestamp"]}\n{header_dic["nonce_str"]}\n{json.dumps(data)}\n'
        key = RSA.importKey(user.public_key)
        rand_hash = SHA256.new()
        rand_hash.update(message.replace(' ', '').encode())
        rand_hash1 = SHA256.new()
        rand_hash1.update(message1.replace(' ', '').encode())
        rand_hash2 = SHA256.new()
        rand_hash2.update(message.encode())
        rand_hash3 = SHA256.new()
        rand_hash3.update(message1.encode())
        verifier = sign_PKCS1_v1_5.new(key)
        if not verifier.verify(rand_hash, base64.b64decode(header_dic['signature'] + '==')) and not \
                verifier.verify(rand_hash1, base64.b64decode(header_dic['signature'] + '==')) and not \
                verifier.verify(rand_hash2, base64.b64decode(header_dic['signature'] + '==')) and not \
                verifier.verify(rand_hash3, base64.b64decode(header_dic['signature'] + '==')):
            return Response({'code': 400, 'message': '签名错误', 'sub_code': 'SYSTEM_EXCEPTION'}, status=status.HTTP_200_OK)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=activity_id, coupon_way=5, coupon_channel=1, coupon_status=1)
        except:
            return Response({'code': 400, 'message': '无效活动id', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = AliDiscountCouponAPIRelation.objects.filter(developer_id=user.id, alidiscountcoupon_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限派发当前活动', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        activity_id = activity.id
        # alidiscountcoupon_level = AliDiscountCouponLevel.objects.filter(activity_id=activity.id).first()
        out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'

        try:
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.distributed_limit_by_time == 1:
                week = str(datetime.datetime.now().weekday())
                enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                if not alidiscountcoupondstributedlimit:
                    return Response({'code': 400, 'message': '没到活动派发时间', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        except:
            pass
        if activity.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
            if max_no >= activity.max_number_by_day:
                return Response({'code': 400, 'message': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        if activity.max_number_by_user:
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, login_id=login_id).count()
            if max_no >= activity.max_number_by_user:
                return Response({'code': 400, 'message': '用户参与活动次数已达上限，感谢您对本活动的支持！', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        if activity.remain_number <= 0:
            return Response({'code': 400, 'message': '活动已达到派发上限！', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        # alidiscountcoupon_level_id = alidiscountcoupon_level.id
        alipay_obj = c_AlipayOpen()
        template_id = activity.template_id
        result = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
        if result['code'] != '10000':
            logger.error(str(result))
            try:
                return Response({'code': 400, 'message': result['sub_msg'], 'sub_code': result['sub_code']},status=status.HTTP_200_OK)
            except:
                return Response({'code': 400, 'message': '领取失败,请联系管理员', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        voucher_id = result['voucher_id']
        result = json.loads(alipay_obj.voucherquery(voucher_id))
        data = {
            'alidiscountcoupon_id': activity.id,
            'voucher_id': voucher_id,
            'template_id': result['template_id'],
            'gmt_active': result['gmt_active'],
            'gmt_expired': result['gmt_expired'],
            'total_amount': result['total_amount'],
            'gmt_create': result['gmt_create'],
            'available_amount': result['available_amount'],
            'name': result['name'],
            'out_biz_no': out_biz_no,
            'gmt_distributed': datetime.datetime.now(),
            # 'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
            'level_id': activity.level_id,
            'login_id': login_id,
            'mobile': mobile,
            'companyuser_id': user.id,
            'coupon_channel': activity.coupon_channel
        }
        # a = 0
        # while True:
        #     if a >= 20:
        #         break
        #     alidiscountcoupon_level = AliDiscountCouponLevel.objects.get(id=alidiscountcoupon_level_id)
        #     instance_origin_take_number = alidiscountcoupon_level.take_number
        #     instance_origin_receive_number = alidiscountcoupon_level.receive_number
        #     instance_origin_remain_number = alidiscountcoupon_level.remain_number
        #     instance_origin_p_take_number = alidiscountcoupon_level.p_take_number
        #     instance_origin_p_receive_number = alidiscountcoupon_level.p_receive_number
        #     instance_origin_p_remain_number = alidiscountcoupon_level.p_remain_number
        #     instance_new_take_number = instance_origin_take_number + 1
        #     instance_new_receive_number = instance_origin_receive_number + 1
        #     instance_new_remain_number = instance_origin_remain_number - 1
        #     instance_new_p_take_number = instance_origin_p_take_number + 1
        #     instance_new_p_receive_number = instance_origin_p_receive_number + 1
        #     instance_new_p_remain_number = instance_origin_p_remain_number - 1
        #     result = AliDiscountCouponLevel.objects.filter(id=alidiscountcoupon_level_id,take_number=instance_origin_take_number).update(
        #         take_number=instance_new_take_number,
        #         receive_number=instance_new_receive_number,
        #         remain_number=instance_new_remain_number,
        #         p_take_number=instance_new_p_take_number,
        #         p_receive_number=instance_new_p_receive_number,
        #         p_remain_number=instance_new_p_remain_number
        #     )
        #     if result == 0:
        #         a += 1
        #         continue
        #     break
        a = 0
        while True:
            if a >= 20:
                break
            activity = AliDiscountCoupon.objects.get(id=activity_id)
            activity_origin_send_count = activity.send_count
            activity_origin_remain_number = activity.remain_number
            activity_new_send_count = activity_origin_send_count + 1
            activity_new_remain_number = activity_origin_remain_number - 1
            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                send_count=activity_new_send_count,
                remain_number=activity_new_remain_number
            )
            if result == 0:
                a += 1
                continue
            break
        # try:
        #     relation_set = alidiscountcoupon_level.child_set.all()
        #     for relation in relation_set:
        #         parent = relation.parent
        #         parent.p_take_number += 1
        #         parent.p_receive_number += 1
        #         parent.p_remain_number -= 1
        #         parent.save()
        # except:
        #     pass
        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=voucher_id)
        if create:
            return Response({'code': 200, 'message': '领取成功', 'voucher_id': voucher_id}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 400, 'message': '已经领取过了'}, status=status.HTTP_200_OK)

    def coupons(self, request):
        headers = request.META.get('HTTP_AUTHORIZATION')
        data = self.request.data
        activity_id = data.get('activity_id', None)
        openid = data.get('openid', None)
        appid = data.get('appid', None)
        mobile = data.get('mobile', None)
        try:
            header_list = headers.split(',')
        except:
            return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        header_dic = {}
        for header in header_list:
            if header:
                try:
                    header = header.split('=')
                    header_dic[header[0]] = header[1]
                except:
                    return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if ('company' and 'timestamp' and 'nonce_str' and 'signature') not in header_dic:
            return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '活动参数必传', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '请上传领取用户手机号mobile', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return Response({'code': 400, 'message': '您输入的手机号格式不正确', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not openid:
            return Response({'code': 400, 'message': '微信用户标识openid参数必传', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not appid:
            return Response({'code': 400, 'message': '需要传入appid,且与接口传入中的openid有对应关系', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(account=header_dic['company'], is_active=1)
        except:
            return Response({'code': 400, 'message': '无效接入方标识', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not user.is_developer:
            return Response({'code': 400, 'message': '用户尚未开通权限', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        message = f'POST\n/voucher/coupons/\n{header_dic["timestamp"]}\n{header_dic["nonce_str"]}\n{json.dumps(data, ensure_ascii=False)}\n'
        message1 = f'POST\n/voucher/coupons/\n{header_dic["timestamp"]}\n{header_dic["nonce_str"]}\n{json.dumps(data)}\n'
        key = RSA.importKey(user.public_key)
        rand_hash = SHA256.new()
        rand_hash.update(message.replace(' ', '').encode())
        rand_hash1 = SHA256.new()
        rand_hash1.update(message1.replace(' ', '').encode())
        rand_hash2 = SHA256.new()
        rand_hash2.update(message.encode())
        rand_hash3 = SHA256.new()
        rand_hash3.update(message1.encode())
        verifier = sign_PKCS1_v1_5.new(key)
        if not verifier.verify(rand_hash, base64.b64decode(header_dic['signature'] + '==')) and not \
                verifier.verify(rand_hash1, base64.b64decode(header_dic['signature'] + '==')) and not \
                verifier.verify(rand_hash2, base64.b64decode(header_dic['signature'] + '==')) and not \
                verifier.verify(rand_hash3, base64.b64decode(header_dic['signature'] + '==')):
            return Response({'code': 400, 'message': '签名错误', 'sub_code': 'SYSTEM_EXCEPTION'}, status=status.HTTP_200_OK)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=activity_id, coupon_way=5, coupon_channel=2, coupon_status=1)
        except:
            return Response({'code': 400, 'message': '无效活动id', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = AliDiscountCouponAPIRelation.objects.filter(developer_id=user.id, alidiscountcoupon_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限派发当前活动', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        activity_id = activity.id
        # alidiscountcoupon_level = AliDiscountCouponLevel.objects.filter(activity_id=activity.id).first()
        out_biz_no = f'100004{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'

        try:
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.distributed_limit_by_time == 1:
                week = str(datetime.datetime.now().weekday())
                enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                if not alidiscountcoupondstributedlimit:
                    return Response({'code': 400, 'message': '没到活动派发时间', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        except:
            pass
        if activity.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
            if max_no >= activity.max_number_by_day:
                return Response({'code': 400, 'message': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        if activity.max_number_by_user:
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, user_id=openid).count()
            if max_no >= activity.max_number_by_user:
                return Response({'code': 400, 'message': '用户参与活动次数已达上限，感谢您对本活动的支持！', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        if activity.remain_number <= 0:
            return Response({'code': 400, 'message': '活动已达到派发上限！', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        if activity.platform_id == 13:
            distribute_channel = Channel.objects.get(id=13)
        else:
            distribute_channel = Channel.objects.get(id=9)
        data_json = {
            "stock_id": activity.template_id,
            "out_request_no": out_biz_no,
            "appid": appid,
            "stock_creator_mchid": activity.platform.mchid
        }
        data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
        if 'code' in data_dict:
            return Response({'code': 400, 'message': data_dict['message'], 'sub_code': 'ACTIVITY_NOT_EXIST'},status=status.HTTP_200_OK)
        coupon_id = data_dict['coupon_id']
        result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
        data = {
            'alidiscountcoupon_id': activity.id,
            'voucher_id': coupon_id,
            'user_id': openid,
            'template_id': result['stock_id'],
            'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
            'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
            'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
            'gmt_create': datetime.datetime.now(),
            'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
            'name': result['coupon_name'],
            'out_biz_no': out_biz_no,
            # 'customer_user_id': user.id,
            'gmt_distributed': datetime.datetime.now(),
            # 'alidiscountcoupon_level_id': alidiscountcoupon_level.id,
            'level_id': activity.level_id,
            'mobile': mobile,
            'companyuser_id': user.id,
            'appid': appid,
            'coupon_channel': activity.coupon_channel
        }

        a = 0
        while True:
            if a >= 20:
                break
            activity = AliDiscountCoupon.objects.get(id=activity_id)
            activity_origin_send_count = activity.send_count
            activity_origin_remain_number = activity.remain_number
            activity_new_send_count = activity_origin_send_count + 1
            activity_new_remain_number = activity_origin_remain_number - 1
            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                send_count=activity_new_send_count,
                remain_number=activity_new_remain_number
            )
            if result == 0:
                a += 1
                continue
            break
        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
        if create:
            return Response({'code': 200, 'message': '领取成功', 'voucher_id': coupon_id}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 400, 'message': '已经领取过了'}, status=status.HTTP_200_OK)

    def query(self, request):
        headers = request.META.get('HTTP_AUTHORIZATION')
        voucher_id = self.request.query_params.get('voucher_id', None)
        try:
            header_list = headers.split(',')
        except:
            return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        header_dic = {}
        for header in header_list:
            if header:
                try:
                    header = header.split('=')
                    header_dic[header[0]] = header[1]
                except:
                    return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if ('company' and 'timestamp' and 'nonce_str' and 'signature') not in header_dic:
            return Response({'code': 400, 'message': 'http header中参数格式错误', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not voucher_id:
            return Response({'code': 400, 'message': '请上传优惠券id', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(account=header_dic['company'], is_active=1)
        except:
            return Response({'code': 400, 'message': '无效接入方标识', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        if not user.is_developer:
            return Response({'code': 400, 'message': '用户尚未开通权限', 'sub_code': 'ILLEGAL_ARGUMENTS'}, status=status.HTTP_200_OK)
        message = f'GET\n/voucher/query/?voucher_id={voucher_id}\n{header_dic["timestamp"]}\n{header_dic["nonce_str"]}\n\n'
        key = RSA.importKey(user.public_key)
        rand_hash = SHA256.new()
        rand_hash.update(message.replace(' ', '').encode())
        verifier = sign_PKCS1_v1_5.new(key)
        if not verifier.verify(rand_hash, base64.b64decode(header_dic['signature'] + '==')):
            return Response({'code': 400, 'message': '签名错误', 'sub_code': 'SYSTEM_EXCEPTION'}, status=status.HTTP_200_OK)
        try:
            alidiscountcouponinfo = AliDiscountCouponInfo.objects.get(voucher_id=voucher_id, companyuser_id=user.id)
        except:
            return Response({'code': 400, 'message': '无效优惠券id', 'sub_code': 'ACTIVITY_NOT_EXIST'}, status=status.HTTP_200_OK)
        alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
        data = {}
        data['activity_id'] = alidiscountcoupon.template_id
        data['activity_name'] = alidiscountcoupon.activity_name
        data['status'] = alidiscountcouponinfo.status
        data['status_display'] = alidiscountcouponinfo.get_status_display()
        data['create_time'] = alidiscountcouponinfo.gmt_create.strftime("%Y-%m-%d %H:%M:%S")
        data['expired_time'] = alidiscountcouponinfo.gmt_expired.strftime("%Y-%m-%d %H:%M:%S")
        data['mobile'] = alidiscountcouponinfo.mobile
        if alidiscountcouponinfo.gmt_use:
            data['use_time'] = alidiscountcouponinfo.gmt_use.strftime("%Y-%m-%d %H:%M:%S")
        else:
            data['use_time'] = ''
        return Response({'code': 200, 'message': '', 'data': data}, status=status.HTTP_200_OK)

    def distribuye(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            logger_vouchers.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        activity_id = data.get('activity_id', None)
        mobile = data.get('user', None)
        tel = data.get('mobile', None)
        login_id = data.get('login_id', None)
        appid = data.get('appid', None)
        openid = data.get('openid', None)
        out_biz_order = data.get('out_biz_no', None)
        notify_url = data.get('notify_url', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not out_biz_order:
            return Response({'code': 400, 'message': '缺少out_biz_no参数'}, status=status.HTTP_200_OK)
        if not notify_url:
            return Response({'code': 400, 'message': '缺少notify_url参数'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '缺少user参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        if not tel:
            return Response({'code': 400, 'message': '缺少mobile参数'}, status=status.HTTP_200_OK)
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return Response({'code': 400, 'message': 'mobile参数请上传手机格式'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        if len(out_biz_order) > 32:
            return Response({'code': 400, 'message': 'out_biz_no参数格式有误'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        check_instance = AliDiscountCouponInfo.objects.filter(out_biz_order=out_biz_order)
        if check_instance:
            if user.id == 24:
                return Response({'code': 200, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
            elif user.id == 65375:
                return Response({'code': 200, 'message': '上传成功'}, status=status.HTTP_200_OK)
            else:
                return Response({'code': 400, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=activity_id, coupon_way=5, coupon_status=1, coupon_channel__in=[1, 2, 3])
        except:
            return Response({'code': 400, 'message': '无效活动id'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = AliDiscountCouponAPIRelation.objects.filter(developer_id=user.id, alidiscountcoupon_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限派发当前活动'}, status=status.HTTP_200_OK)
        if activity.coupon_channel == 1:
            if not login_id:
                return Response({'code': 400, 'message': '缺少login_id参数'}, status=status.HTTP_200_OK)
        elif activity.coupon_channel in [2, 3]:
            appid_white_table = APIWhiteTable.objects.filter(char=appid)
            if not appid_white_table:
                return Response({'code': 400, 'message': '无效接入appid'}, status=status.HTTP_200_OK)
            if not openid:
                return Response({'code': 400, 'message': '缺少openid参数'}, status=status.HTTP_200_OK)
            if len(openid) > 32:
                return Response({'code': 400, 'message': 'openid参数格式有误'}, status=status.HTTP_200_OK)
        if activity.remain_number <= 0:
            return Response({'code': 400, 'message': '活动额度已消耗完'}, status=status.HTTP_200_OK)
        try:
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.distributed_limit_by_time == 1:
                week = str(datetime.datetime.now().weekday())
                enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                if not alidiscountcoupondstributedlimit:
                    return Response({'code': 400, 'message': '没到活动派发时间'}, status=status.HTTP_200_OK)
        except:
            pass
        if activity.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
            if max_no >= activity.max_number_by_day:
                return Response({'code': 400, 'message': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_200_OK)
        if activity.max_number_by_user:
            if activity.coupon_channel == 1:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, login_id=login_id).count()
                if max_no >= activity.max_number_by_user:
                    return Response({'code': 400, 'message': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_200_OK)
            else:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, user_id=openid).count()
                if max_no >= activity.max_number_by_user:
                    return Response({'code': 400, 'message': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_200_OK)
        activity_id = activity.id
        out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        a = 0
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                while True:
                    if a >= 20:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '系统繁忙'}, status=status.HTTP_200_OK)
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    if activity.remain_number <= 0:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '活动额度已消耗完'}, status=status.HTTP_200_OK)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        a += 1
                        continue
                    break
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'template_id': activity_id,
                    'out_biz_no': out_biz_no,
                    'gmt_distributed': datetime.datetime.now(),
                    'login_id': login_id,
                    'companyuser_id': user.id,
                    'appid': appid,
                    'user_id': openid,
                    'out_biz_order': out_biz_order,
                    'status': 0,
                    'mobile': tel,
                    'notify_url': notify_url,
                    'coupon_channel': activity.coupon_channel,
                    'level_id': activity.level_id
                }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_order=out_biz_order)
                transaction.savepoint_commit(save_id)
                if create:
                    task_id = dispose_voucher_result.delay({"id": voucherinfo.id})
                    # task_id = dispose_voucher_result({"id": voucherinfo.id})
                    return Response({'code': 200, 'message': '上传成功'}, status=status.HTTP_200_OK)
                else:
                    return Response({'code': 400, 'message': '已经领取过了'}, status=status.HTTP_200_OK)
            except:
                transaction.savepoint_rollback(save_id)
                return Response({'code': 400, 'message': '系统繁忙'}, status=status.HTTP_200_OK)

    def inquire(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        out_biz_order = data.get('out_biz_no', None)
        mobile = data.get('user', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not out_biz_order:
            return Response({'code': 400, 'message': '缺少out_biz_no参数'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        alidiscountcouponinfo = AliDiscountCouponInfo.objects.filter(out_biz_order=out_biz_order, companyuser_id=user.id).first()
        if not alidiscountcouponinfo:
            return Response({'code': 400, 'message': '派发申请单不存在'}, status=status.HTTP_200_OK)
        request_data = {}
        request_data['code'] = 200
        request_data['message'] = '查询成功'
        alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
        if alidiscountcouponinfo.status in [1, 8, 9]:
            if alidiscountcoupon.coupon_channel == 1:
                alipayopen = AlipayOpen()
                result = json.loads(alipayopen.voucherquery(alidiscountcouponinfo.voucher_id))
                if result['status'] == 'USED':
                    alidiscountcoupon.use_count += 1
                    alidiscountcoupon.save()
                    try:
                        if 'bill_details' in result:
                            for bill_datail in result['bill_details']:
                                alidiscountcouponinfo.gmt_use = bill_datail['gmt_create']
                                bill_datail['voucherinfo_id'] = alidiscountcouponinfo.id
                                AliDiscountCouponBillDetails.objects.create(**bill_datail)
                    except:
                        pass
                    try:
                        alidiscountcoupon_level = alidiscountcouponinfo.alidiscountcoupon_level
                        alidiscountcoupon_level.use_number += 1
                        alidiscountcoupon_level.p_use_number += 1
                        alidiscountcoupon_level.save()
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_use_number += 1
                            parent.save()
                    except:
                        pass
                alidiscountcouponinfo.status = alidiscountcouponinfo.STATUS_ENUM[result['status']]
                alidiscountcouponinfo.save()
            elif alidiscountcoupon.coupon_channel == 2:
                coupon_id = alidiscountcouponinfo.voucher_id
                openid = alidiscountcouponinfo.user_id
                appid = alidiscountcouponinfo.appid
                if alidiscountcoupon.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=9)
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                try:
                    if result['status'] == 'USED':
                        alidiscountcoupon.use_count += 1
                        alidiscountcoupon.save()
                        try:
                            if 'bill_details' in result:
                                for bill_datail in result['bill_details']:
                                    alidiscountcouponinfo.gmt_use = bill_datail['gmt_create']
                                    bill_datail['voucherinfo_id'] = alidiscountcouponinfo.id
                                    AliDiscountCouponBillDetails.objects.create(**bill_datail)
                        except:
                            pass
                        try:
                            alidiscountcoupon_level = alidiscountcouponinfo.alidiscountcoupon_level
                            alidiscountcoupon_level.use_number += 1
                            alidiscountcoupon_level.p_use_number += 1
                            alidiscountcoupon_level.save()
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_use_number += 1
                                parent.save()
                        except:
                            pass
                        alidiscountcouponinfo.status = 7
                        alidiscountcouponinfo.gmt_use = datetime.datetime.now()
                    elif result['status'] == 'EXPIRED':
                        alidiscountcouponinfo.status = 12
                    alidiscountcouponinfo.save()
                except:
                    pass
        if alidiscountcouponinfo.status == 14:
            if user.id == 65375:
                request_data['code'] = 400
                request_data['message'] = '领取失败'
            data = {}
            data['voucher_id'] = ''
            data['activity_id'] = alidiscountcoupon.template_id
            data['activity_name'] = alidiscountcoupon.activity_name
            data['status_display'] = alidiscountcouponinfo.get_status_display()
            data['status'] = alidiscountcouponinfo.status
            data['create_time'] = alidiscountcouponinfo.gmt_distributed.strftime("%Y-%m-%d %H:%M:%S")
            data['expired_time'] = ''
            data['mobile'] = alidiscountcouponinfo.mobile
            data['out_biz_no'] = alidiscountcouponinfo.out_biz_order
            data['use_time'] = ''
            data['return_msg'] = alidiscountcouponinfo.return_msg
        else:
            data = {}
            data['voucher_id'] = alidiscountcouponinfo.voucher_id
            data['activity_id'] = alidiscountcoupon.template_id
            data['activity_name'] = alidiscountcoupon.activity_name
            data['status_display'] = alidiscountcouponinfo.get_status_display()
            data['status'] = alidiscountcouponinfo.status
            data['create_time'] = alidiscountcouponinfo.gmt_distributed.strftime("%Y-%m-%d %H:%M:%S")
            if alidiscountcouponinfo.gmt_expired:
                data['expired_time'] = alidiscountcouponinfo.gmt_expired.strftime("%Y-%m-%d %H:%M:%S")
            else:
                data['expired_time'] = ''
            data['mobile'] = alidiscountcouponinfo.mobile
            data['out_biz_no'] = alidiscountcouponinfo.out_biz_order
            if alidiscountcouponinfo.gmt_use:
                data['use_time'] = alidiscountcouponinfo.gmt_use.strftime("%Y-%m-%d %H:%M:%S")
            else:
                data['use_time'] = ''
            if alidiscountcouponinfo.gmt_active:
                data['active_time'] = alidiscountcouponinfo.gmt_active.strftime("%Y-%m-%d %H:%M:%S")
            else:
                data['active_time'] = ''
            data['return_msg'] = ''
        if alidiscountcoupon.coupon_channel == 3:
            if user.id in [1, 404]:
                linkUrl = f'pages/ylx_transition/ylx_transition?path=pages/coupon_pro_list/coupon_pro_list&coupon_id={alidiscountcouponinfo.voucher_id}'
                linkAppId = 'wx950122ad80dc97c9'
                contentLink = {
                    "linkAppId": linkAppId,
                    "linkUrl": linkUrl
                }
                data['contentLink'] = contentLink
        if user.id in [1, 40535]:
            ciphertext = encrypt_pkcs7_padding(json.dumps(data), user.authen_key)
            data = {"ciphertext": ciphertext}
        request_data['data'] = data
        return Response(request_data, status=status.HTTP_200_OK)

    def activity(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        print(self.request.data)
        try:
            logger_vouchers.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        activity_id = data.get('activity_id', None)
        mobile = data.get('user', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=activity_id, coupon_way=5, coupon_status=1)
        except:
            return Response({'code': 400, 'message': '无效活动id'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = AliDiscountCouponAPIRelation.objects.filter(developer_id=user.id, alidiscountcoupon_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限查阅当前活动'}, status=status.HTTP_200_OK)
        request_data = {}
        request_data['code'] = 200
        request_data['message'] = '查询成功'
        data = {}
        data['activity_id'] = activity.template_id
        data['activity_name'] = activity.activity_name
        data['coupon_status_display'] = activity.get_coupon_status_display()
        data['coupon_status'] = activity.coupon_status
        data['publish_start_time'] = activity.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
        data['publish_end_time'] = activity.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
        data['floor_amount'] = activity.floor_amount
        data['max_number'] = activity.max_number
        data['send_number'] = activity.send_count
        data['remain_number'] = activity.remain_number
        data['coupon_channel_display'] = activity.get_coupon_channel_display()
        data['coupon_channel'] = activity.coupon_channel
        data['description'] = activity.activity_description
        data['amount'] = activity.amount
        data['transaction_minimum'] = activity.transaction_minimum
        request_data['data'] = data
        return Response({'code': 200, 'message': '', 'data': data}, status=status.HTTP_200_OK)

    def ysh_distribuye(self, request):
        # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        # if x_forwarded_for:
        #     ip = x_forwarded_for.split(',')[0]
        # else:
        #     ip = request.META.get('REMOTE_ADDR')
        # print(ip)
        # ip_white_table = APIWhiteTable.objects.filter(char=ip)
        # if not ip_white_table:
        #     return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        HTTP_SIGN_APP_ID = request.META.get('HTTP_SIGN_APP_ID')
        HTTP_SIGN_APP_NONCE = request.META.get('HTTP_SIGN_APP_NONCE')
        HTTP_SIGN_APP_SIGNTURE = request.META.get('HTTP_SIGN_APP_SIGNTURE')
        HTTP_SIGN_APP_TIMESTAMP = request.META.get('HTTP_SIGN_APP_TIMESTAMP')
        request_data = self.request.data.get('data', None)
        method = self.request.data.get('method', None)
        key = 'HO8pOzQJxJCwJcYP0likhOLTVezBnk89'
        iv = 'YYZHbxUFOyO1g5Qv'
        secret = 'MM1Q8oOOxeUTbI34QfNA39EPdjZ3aa7u'
        data_dict = {'method': method}
        data_dict['data'] = request_data
        data_dict['nonce'] = HTTP_SIGN_APP_NONCE
        data_dict['timestamp'] = HTTP_SIGN_APP_TIMESTAMP
        data_dict['appId'] = HTTP_SIGN_APP_ID
        response_data = {}
        meta = {}
        data = {}
        distribution = {}
        data['distribution'] = distribution
        response_data['data'] = data
        meta['code'] = ''
        meta['msg'] = ''
        meta['requestId'] = str(uuid.uuid4())
        response_data['meta'] = meta
        try:
            signture = get_sign(data_dict, secret)
            if signture != HTTP_SIGN_APP_SIGNTURE:
                meta['code'] = '100004'
                meta['msg'] = '验签不通过'
                return Response({'retMessage': '请求成功', 'reCode': '1', 'data': response_data}, status=status.HTTP_200_OK)
            user_id = 64746
            body = json.loads(decrypt(request_data, key, iv))
            equityId = body.get('equityId', None)
            orderNo = body.get('orderNo', None)
            unionId = body.get('unionId', None)
            chargeAccount = body.get('chargeAccount', None)
            receiveMode = body.get('receiveMode', None)
            wxMiniAppId = body.get('wxMiniAppId', None)
            wxMiniOpenId = body.get('wxMiniOpenId', None)
            usageType = body.get('usageType', None)
            userDistCode = body.get('userDistCode', None)
            if not equityId:
                meta['code'] = '300'
                meta['msg'] = '缺少euqityId参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not orderNo:
                meta['code'] = '300'
                meta['msg'] = '缺少orderNo参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not unionId:
                meta['code'] = '300'
                meta['msg'] = '缺少unionId参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not chargeAccount:
                meta['code'] = '300'
                meta['msg'] = '缺少chargeAccount参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not receiveMode:
                meta['code'] = '300'
                meta['msg'] = '缺少receiveMode参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not wxMiniAppId:
                meta['code'] = '300'
                meta['msg'] = '缺少wxMiniAppId参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not wxMiniOpenId:
                meta['code'] = '300'
                meta['msg'] = '缺少wxMiniOpenId参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not usageType:
                meta['code'] = '300'
                meta['msg'] = '缺少usageType参数'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            # if not userDistCode:
            #     meta['code'] = '300'
            #     meta['msg'] = '缺少userDistCode参数'
            #     response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
            #     return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            check_alidiscountcouponinfo = AliDiscountCouponInfo.objects.filter(out_biz_order=orderNo).first()
            if check_alidiscountcouponinfo:
                distribution['id'] = check_alidiscountcouponinfo.voucher_id
                distribution['equityId'] = equityId
                distribution['status'] = 'RECEIVED'
                distribution['order_no'] = orderNo
                meta['code'] = '200'
                meta['msg'] = 'success'
                # response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
                # meta['code'] = '400'
                # meta['msg'] = '重复orderNo请求'
                # response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            try:
                ysh_alidiscountcoupon = YSHAliDiscountCoupon.objects.get(equityId=equityId)
            except:
                meta['code'] = '300'
                meta['msg'] = '无效卡券'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            activity = ysh_alidiscountcoupon.alidiscountcoupon
            if activity.coupon_way != 5:
                meta['code'] = '300'
                meta['msg'] = '无效卡券'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if activity.coupon_status == 2:
                meta['code'] = '300'
                meta['msg'] = '活动已结束'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if activity.coupon_channel != 2:
                meta['code'] = '300'
                meta['msg'] = '无效卡券'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if not re.match(r'^1[3-9]\d{9}$', chargeAccount):
                meta['code'] = '300'
                meta['msg'] = 'chargeAccount参数请上传手机格式'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if usageType != ysh_alidiscountcoupon.USAGE_TYPE_ENUM[ysh_alidiscountcoupon.usageType]:
                meta['code'] = '300'
                meta['msg'] = '卡券使用类型与活动配置有误'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
            if channelcommonvoucher.distributed_limit_by_time == 1:
                week = str(datetime.datetime.now().weekday())
                enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
                alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
                if not alidiscountcoupondstributedlimit:
                    meta['code'] = '300'
                    meta['msg'] = '没到活动派发时间'
                    response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                    return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if activity.max_number_by_day:
                begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
                end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
                if max_no >= activity.max_number_by_day:
                    meta['code'] = '300'
                    meta['msg'] = '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'
                    response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                    return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if activity.max_number_by_user:
                max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, user_id=wxMiniOpenId).count()
                if max_no >= activity.max_number_by_user:
                    meta['code'] = '300'
                    meta['msg'] = '用户参与活动次数已达上限，感谢您对本活动的支持！'
                    response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                    return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            if activity.remain_number <= 0:
                meta['code'] = '300'
                meta['msg'] = '没到活动派发时间'
                response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
            activity_id = activity.id
            out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
            a = 0
            with transaction.atomic():
                save_id = transaction.savepoint()
                try:
                    while True:
                        if a >= 20:
                            transaction.savepoint_rollback(save_id)
                            meta['code'] = '300'
                            meta['msg'] = '系统繁忙'
                            response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                            return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
                        activity = AliDiscountCoupon.objects.get(id=activity_id)
                        if activity.remain_number <= 0:
                            transaction.savepoint_rollback(save_id)
                            meta['code'] = '300'
                            meta['msg'] = '活动额度已消耗完'
                            response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                            return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
                        activity_origin_send_count = activity.send_count
                        activity_origin_remain_number = activity.remain_number
                        activity_new_send_count = activity_origin_send_count + 1
                        activity_new_remain_number = activity_origin_remain_number - 1
                        result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                        if result == 0:
                            a += 1
                            continue
                        break
                    out_biz_no = out_biz_no
                    appid = wxMiniAppId
                    openid = wxMiniOpenId
                    if activity.platform_id == 13:
                        distribute_channel = Channel.objects.get(id=13)
                    else:
                        distribute_channel = Channel.objects.get(id=9)
                    data_json = {
                        "stock_id": activity.template_id,
                        "out_request_no": out_biz_no,
                        "appid": appid,
                        "stock_creator_mchid": activity.platform.mchid
                    }
                    data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                    if 'code' in data_dict:
                        transaction.savepoint_rollback(save_id)
                        meta['code'] = '300'
                        meta['msg'] = data_dict['message']
                        response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                        return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
                    coupon_id = data_dict['coupon_id']
                    result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                    data = {
                        'alidiscountcoupon_id': activity.id,
                        'voucher_id': coupon_id,
                        'user_id': openid,
                        'template_id': result['stock_id'],
                        'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                        'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                        'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                        'gmt_create': datetime.datetime.now(),
                        'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                        'name': result['coupon_name'],
                        'out_biz_no': out_biz_no,
                        'gmt_distributed': datetime.datetime.now(),
                        'mobile': chargeAccount,
                        'companyuser_id': user_id,
                        'appid': appid,
                        'coupon_channel': activity.coupon_channel,
                        'level_id': activity.level_id,
                        'out_biz_order': orderNo,
                        'notify_url': userDistCode
                    }
                    voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, voucher_id=coupon_id)
                    distribution['id'] = coupon_id
                    distribution['equityId'] = equityId
                    distribution['status'] = 'RECEIVED'
                    distribution['order_no'] = orderNo
                    transaction.savepoint_commit(save_id)
                    meta['code'] = '200'
                    meta['msg'] = 'success'
                    # response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                    return Response({'data': encrypt(json.dumps(response_data).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
                except:
                    transaction.savepoint_rollback(save_id)
                    meta['code'] = '400'
                    meta['msg'] = '系统繁忙'
                    response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
                    return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)
        except:
            meta['code'] = '400'
            meta['msg'] = '系统繁忙'
            response_data1 = {'retMessage': '请求成功', 'reCode': '1', 'data': response_data}
            return Response({'data': encrypt(json.dumps(response_data1).replace(' ', ''), key, iv)}, status=status.HTTP_200_OK)

    def ysh_merchant(self, request):
        identify = self.request.query_params.get('identify', None)
        latitude = self.request.query_params.get('latitude', None)
        longitude = self.request.query_params.get('longitude', None)
        search = self.request.query_params.get('search', None)
        yshalidiscountcoupon = YSHAliDiscountCoupon.objects.filter(identify=identify).first()
        if yshalidiscountcoupon:
           alidiscountcoupon_id = yshalidiscountcoupon.alidiscountcoupon_id
           if not all([latitude, longitude]):
               queryset = Merchant.objects.filter(alidiscountcouponmerchant__alidiscountcoupon_id=alidiscountcoupon_id, latitude__isnull=False).exclude(latitude='').distinct()
           else:
               gcd_formula = "6371 * acos(least(greatest(cos(radians(%s)) * cos(radians(latitude)) * cos(radians(longitude) - radians(%s)) + sin(radians(%s)) * sin(radians(latitude)) , -1), 1))"
               sql = RawSQL(gcd_formula, (latitude, longitude, latitude))
               queryset = Merchant.objects.filter(latitude__isnull=False, alidiscountcouponmerchant__alidiscountcoupon_id=alidiscountcoupon_id).exclude(latitude='').distinct().annotate(distance=sql).order_by(F('distance').asc(nulls_last=True))
           if search:
               queryset = queryset.filter(Q(short_name__contains=search) | Q(name__contains=search))
        else:
            queryset = Merchant.objects.filter(id=0)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = MerchantListModelSerializer(page, many=True, context={'longitude': longitude, 'latitude': latitude})
            return self.get_paginated_response(serializer.data)
        serializer = MerchantListModelSerializer(page, many=True, context={'longitude': longitude, 'latitude': latitude})
        return Response(serializer.data)

    def haizhui(self, request):
        identify = self.request.query_params.get('id', None)
        qrcode = AliDiscountCouponQRCode.objects.filter(identify=identify).first()
        alidiscountcoupon_level = qrcode.alidiscountcoupon_level
        activity = alidiscountcoupon_level.activity
        floor_amount = activity.floor_amount
        amount = activity.amount
        activity_name = activity.activity_name
        activity_valid_period = activity.activity_valid_period
        publish_start_time = activity.publish_start_time.strftime('%Y-%m-%d %H:%M:%S')
        publish_end_time = activity.publish_end_time.strftime('%Y-%m-%d %H:%M:%S')
        if qrcode:
            return render(request, 'haolihui.html', {'common_qrcode': qrcode.common_qrcode.url, 'floor_amount': floor_amount, 'amount': amount, "activity_name": activity_name, 'publish_start_time': publish_start_time, 'publish_end_time': publish_end_time, "activity_valid_period": activity_valid_period})
        else:
            return render(request, 'h5_fill_fail.html', {'data': '二维码已失效'})

    def meituan_result(self, request):
        body = {
            "status": "success",
            "sign": "Gr1PWuXV270OmK4SOPbyDWg9LaCbOgP7iY606ImEMfW6PnJzFUAlUT0gg6XMvyt46belb4xOnRwLyvlC5CE2k1A2HRZvDNpPVh5Da4WEYqKk7kZmTCWJaK1ktw8xNq4JTFiWkueBtJilxSdVrLx1n9hHpg/DYYE+qP6N7FmO/uQeRAElCndnFFifVWjhYpcFUqhJcw9vYT9C/oPzM+romGlCzW5Jrr3MnoP67xTXqfWFd7tfk+ymLN16p1STiSJtOPiJg9LfFLbntc3fL7mi2ltjRWpelAwpiG72zCUAejj/PmHfo2lYYY7lM1/6z2+2Vo+cKv/F8LeiToZo/WKyUQ=="
        }
        try:
            data = self.request.data.copy()
            logger.info(str(data))
            return Response(body, status=status.HTTP_200_OK)
        except Exception as e:
            logger.error(e)
            return Response(body, status=status.HTTP_200_OK)

    def haizhui_distribuye(self, request):
        '''好礼汇派券'''
        Appkey = 'SN8958632086'
        AppSeret = 'DBXRZYRVZUI2CTGQOXPOOEVYUCG7Z4XT'
        # Appkey = 'SN3197527788'
        # AppSeret = 'OTB5MG1OVECHDKWH0SBJMXICQSR6CKKM'
        order_no = self.request.query_params.get('order_no', None)
        recharge_account = self.request.query_params.get('recharge_account', None)
        product_no = self.request.query_params.get('product_no', None)
        amount = self.request.query_params.get('amount', None)
        notify_url = self.request.query_params.get('notify_url', None)
        price = self.request.query_params.get('price', None)
        app_id = self.request.query_params.get('app_id', None)
        timestamp = self.request.query_params.get('timestamp', None)
        supplier_no = self.request.query_params.get('supplier_no', None)
        sign = self.request.query_params.get('sign', None)
        if not all([order_no, recharge_account, product_no, amount, price, app_id, timestamp, supplier_no, sign]):
            return Response({'code': 7001, 'message': '请求参数错误'}, status=status.HTTP_200_OK)
        server_timestamp = int(time.time() * 1000)
        try:
            if server_timestamp - int(timestamp) >= 180000:
                return Response({'code': 7002, 'message': '请求超时'})
        except:
            return Response({'code': 7001, 'message': '请求参数错误'}, status=status.HTTP_200_OK)
        if supplier_no != Appkey:
            return Response({'code': 7003, 'message': '供应商账号不存在或错误'}, status=status.HTTP_200_OK)
        sign_data = {}
        sign_data['order_no'] = order_no
        sign_data['recharge_account'] = recharge_account
        sign_data['product_no'] = product_no
        sign_data['amount'] = amount
        if notify_url:
            sign_data['notify_url'] = notify_url
        sign_data['price'] = price
        sign_data['app_id'] = app_id
        sign_data['timestamp'] = timestamp
        sign_data['supplier_no'] = supplier_no
        server_sign = haizhui_get_sign(sign_data, AppSeret)
        if server_sign != sign:
            return Response({'code': 7004, 'message': '签名错误 '}, status=status.HTTP_200_OK)
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 7005, 'message': '请求IP有误'}, status=status.HTTP_200_OK)
        haolihui_alidiscountcoupon = AliDiscountCoupon.objects.filter(product_no=product_no).first()
        if not haolihui_alidiscountcoupon:
            return Response({'code': 7006, 'message': '查询不到产品或产品已下架'}, status=status.HTTP_200_OK)
        if haolihui_alidiscountcoupon.coupon_way != 5:
            return Response({'code': 7006, 'message': '查询不到产品或产品已下架'}, status=status.HTTP_200_OK)
        if haolihui_alidiscountcoupon.coupon_status == 2:
            return Response({'code': 7006, 'message': '查询不到产品或产品已下架'}, status=status.HTTP_200_OK)
        if haolihui_alidiscountcoupon.coupon_channel != 2:
            return Response({'code': 7006, 'message': '查询不到产品或产品已下架'}, status=status.HTTP_200_OK)
        channelcommonvoucher = haolihui_alidiscountcoupon.alidiscountcouponchannelcommonvoucher
        if channelcommonvoucher.distributed_limit_by_time == 1:
            week = str(datetime.datetime.now().weekday())
            enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
            alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
            if not alidiscountcoupondstributedlimit:
                return Response({'code': 7006, 'message': '查询不到产品或产品已下架'}, status=status.HTTP_200_OK)
        if haolihui_alidiscountcoupon.max_number_by_day:
            begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
            end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=haolihui_alidiscountcoupon.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
            if max_no >= haolihui_alidiscountcoupon.max_number_by_day:
                return Response({'code': 7006, 'message': '查询不到产品或产品已下架'}, status=status.HTTP_200_OK)
        if haolihui_alidiscountcoupon.max_number_by_user:
            max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=haolihui_alidiscountcoupon.id, user_id=recharge_account).count()
            if max_no >= haolihui_alidiscountcoupon.max_number_by_user:
                return Response({'code': 7006, 'message': '领取超限'}, status=status.HTTP_200_OK)
        if haolihui_alidiscountcoupon.remain_number <= 0:
            return Response({'code': 7006, 'message': '查询不到产品或产品已下架'}, status=status.HTTP_200_OK)
        check_alidiscountcouponinfo = AliDiscountCouponInfo.objects.filter(out_biz_order=order_no).first()
        if check_alidiscountcouponinfo:
            return Response({'code': 7007, 'message': '请求订单号已存在'}, status=status.HTTP_200_OK)
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                activity_id = haolihui_alidiscountcoupon.id
                out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
                a = 0
                while True:
                    if a >= 20:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 7777, 'message': '系统异常'}, status=status.HTTP_200_OK)
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    if activity.remain_number <= 0:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '活动额度已消耗完'}, status=status.HTTP_200_OK)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        a += 1
                        continue
                    break
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'template_id': activity.template_id,
                    'out_biz_no': out_biz_no,
                    'gmt_distributed': datetime.datetime.now(),
                    'login_id': recharge_account,
                    'companyuser_id': 65449,
                    'appid': app_id,
                    'user_id': recharge_account,
                    'out_biz_order': order_no,
                    'status': 0,
                    'notify_url': notify_url,
                    'coupon_channel': activity.coupon_channel,
                    'level_id': activity.level_id
                }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_order=order_no)
                transaction.savepoint_commit(save_id)
                if create:
                    task_id = haizhui_dispose_voucher_result.delay({"id": voucherinfo.id})
                    # task_id = dispose_voucher_result({"id": voucherinfo.id})
                    return Response({'code': 7000, 'message': '请求通过', 'data': {'order_no': order_no, 'state': 'DISPOSING'}}, status=status.HTTP_200_OK)
                else:
                    return Response({'code': 7000, 'message': '已经领取过了'}, status=status.HTTP_200_OK)
            except:
                transaction.savepoint_rollback(save_id)
                return Response({'code': 7777, 'message': '系统异常'}, status=status.HTTP_200_OK)

    def haizhui_inquire(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 7005, 'message': '请求IP有误'}, status=status.HTTP_200_OK)
        Appkey = 'SN8958632086'
        AppSeret = 'DBXRZYRVZUI2CTGQOXPOOEVYUCG7Z4XT'
        # Appkey = 'SN3197527788'
        # AppSeret = 'OTB5MG1OVECHDKWH0SBJMXICQSR6CKKM'
        order_no = self.request.query_params.get('order_no', None)
        timestamp = self.request.query_params.get('timestamp', None)
        supplier_no = self.request.query_params.get('supplier_no', None)
        sign = self.request.query_params.get('sign', None)
        if not all([order_no, timestamp, supplier_no, sign]):
            return Response({'code': 7001, 'message': '请求参数错误'}, status=status.HTTP_200_OK)
        server_timestamp = int(time.time() * 1000)
        try:
            if server_timestamp - int(timestamp) >= 180000:
                return Response({'code': 7002, 'message': '请求超时'})
        except:
            return Response({'code': 7001, 'message': '请求参数错误'}, status=status.HTTP_200_OK)
        if supplier_no != Appkey:
            return Response({'code': 7003, 'message': '供应商账号不存在或错误'}, status=status.HTTP_200_OK)
        sign_data = {}
        sign_data['order_no'] = order_no
        sign_data['timestamp'] = timestamp
        sign_data['supplier_no'] = supplier_no
        server_sign =haizhui_get_sign(sign_data, AppSeret)
        if server_sign != sign:
            return Response({'code': 7004, 'message': '签名错误 '}, status=status.HTTP_200_OK)
        check_alidiscountcouponinfo = AliDiscountCouponInfo.objects.filter(out_biz_order=order_no).first()
        if not check_alidiscountcouponinfo:
            return Response({'code': 7008, 'message': '请求订单不存在'}, status=status.HTTP_200_OK)
        if check_alidiscountcouponinfo.status == 0:
            return Response({'code': 7000, 'message': '请求通过', 'data': {'order_no': order_no, 'status': 'DISPOSING'}}, status=status.HTTP_200_OK)
        elif check_alidiscountcouponinfo.status in [7,8,9,10]:
            return Response({'code': 7000, 'message': '请求通过', 'data': {'order_no': order_no, 'status': 'VERIFIED_OFF'}}, status=status.HTTP_200_OK)
        elif check_alidiscountcouponinfo.status == 14:
            return Response({'code': 7000, 'message': '请求通过', 'data': {'order_no': order_no, 'status': 'RECHARGE_FAIL'}}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 7000, 'message': '请求通过', 'data': {'order_no': order_no, 'status': 'SUCCESS'}}, status=status.HTTP_200_OK)

    def ylx_activity(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        print(self.request.data)
        try:
            logger_vouchers.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        activity_id = data.get('activity_id', None)
        mobile = data.get('user', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=activity_id, coupon_way=5)
        except:
            return Response({'code': 400, 'message': '无效活动id'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = AliDiscountCouponAPIRelation.objects.filter(developer_id=user.id, alidiscountcoupon_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限查阅当前活动'}, status=status.HTTP_200_OK)
        # if str(activity.coupon_channel) == '1':
        #     alipay_obj = AlipayOpen()
        #     result = json.loads(alipay_obj.activityconfig_query(activity_id))
        # else:
        #     result = get_stockinfo(activity.template_id, activity.platform)
        request_data = {}
        request_data['code'] = 200
        request_data['message'] = '查询成功'
        data = {}
        data['activity_id'] = activity.template_id
        data['activity_name'] = activity.activity_name
        data['coupon_status_display'] = activity.get_coupon_status_display()
        data['coupon_status'] = activity.coupon_status
        data['publish_start_time'] = activity.publish_start_time.strftime("%Y-%m-%d %H:%M:%S")
        data['publish_end_time'] = activity.publish_end_time.strftime("%Y-%m-%d %H:%M:%S")
        data['floor_amount'] = activity.floor_amount
        data['max_number'] = activity.max_number
        data['send_number'] = activity.send_count
        data['remain_number'] = activity.remain_number
        data['coupon_channel_display'] = activity.get_coupon_channel_display()
        data['coupon_channel'] = activity.coupon_channel
        data['description'] = activity.activity_description
        data['amount'] = activity.amount
        data['transaction_minimum'] = activity.transaction_minimum
        request_data['data'] = data
        return Response(request_data, status=status.HTTP_200_OK)

    def ylx_inquire(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        print(self.request.data)
        try:
            logger_vouchers.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        out_biz_order = data.get('out_biz_order', None)
        mobile = data.get('user', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not out_biz_order:
            return Response({'code': 400, 'message': '缺少out_biz_order参数'}, status=status.HTTP_200_OK)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        try:
            alidiscountcouponinfo = AliDiscountCouponInfo.objects.get(out_biz_order=out_biz_order)
        except:
            return Response({'code': 400, 'message': '无效活动id'}, status=status.HTTP_200_OK)
        activity = alidiscountcouponinfo.alidiscountcoupon
        ali_discount_coupon_api_relation = AliDiscountCouponAPIRelation.objects.filter(developer_id=user.id, alidiscountcoupon_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限查阅当前活动'}, status=status.HTTP_200_OK)

        request_data = {}
        request_data['code'] = 200
        request_data['message'] = '查询成功'
        alidiscountcoupon = alidiscountcouponinfo.alidiscountcoupon
        if alidiscountcouponinfo.status in [1, 8, 9]:
            if alidiscountcoupon.coupon_channel == 1:
                alipayopen = AlipayOpen()
                result = json.loads(alipayopen.voucherquery(alidiscountcouponinfo.voucher_id))
                if result['status'] == 'USED':
                    alidiscountcoupon.use_count += 1
                    alidiscountcoupon.save()
                    try:
                        if 'bill_details' in result:
                            for bill_datail in result['bill_details']:
                                alidiscountcouponinfo.gmt_use = bill_datail['gmt_create']
                                bill_datail['voucherinfo_id'] = alidiscountcouponinfo.id
                                AliDiscountCouponBillDetails.objects.create(**bill_datail)
                    except:
                        pass
                    try:
                        alidiscountcoupon_level = alidiscountcouponinfo.alidiscountcoupon_level
                        alidiscountcoupon_level.use_number += 1
                        alidiscountcoupon_level.p_use_number += 1
                        alidiscountcoupon_level.save()
                        relation_set = alidiscountcoupon_level.child_set.all()
                        for relation in relation_set:
                            parent = relation.parent
                            parent.p_use_number += 1
                            parent.save()
                    except:
                        pass
                alidiscountcouponinfo.status = alidiscountcouponinfo.STATUS_ENUM[result['status']]
                alidiscountcouponinfo.save()
            elif alidiscountcoupon.coupon_channel == 2:
                coupon_id = alidiscountcouponinfo.voucher_id
                openid = alidiscountcouponinfo.user_id
                appid = alidiscountcouponinfo.appid
                if alidiscountcoupon.platform_id == 13:
                    distribute_channel = Channel.objects.get(id=13)
                else:
                    distribute_channel = Channel.objects.get(id=9)
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                try:
                    if result['status'] == 'USED':
                        alidiscountcoupon.use_count += 1
                        alidiscountcoupon.save()
                        try:
                            if 'bill_details' in result:
                                for bill_datail in result['bill_details']:
                                    alidiscountcouponinfo.gmt_use = bill_datail['gmt_create']
                                    bill_datail['voucherinfo_id'] = alidiscountcouponinfo.id
                                    AliDiscountCouponBillDetails.objects.create(**bill_datail)
                        except:
                            pass
                        try:
                            alidiscountcoupon_level = alidiscountcouponinfo.alidiscountcoupon_level
                            alidiscountcoupon_level.use_number += 1
                            alidiscountcoupon_level.p_use_number += 1
                            alidiscountcoupon_level.save()
                            relation_set = alidiscountcoupon_level.child_set.all()
                            for relation in relation_set:
                                parent = relation.parent
                                parent.p_use_number += 1
                                parent.save()
                        except:
                            pass
                        alidiscountcouponinfo.status = 7
                        alidiscountcouponinfo.gmt_use = datetime.datetime.now()
                    elif result['status'] == 'EXPIRED':
                        alidiscountcouponinfo.status = 12
                    alidiscountcouponinfo.save()
                except:
                    pass
        if alidiscountcouponinfo.status == 14:
            data = {}
            data['voucher_id'] = ''
            data['activity_id'] = alidiscountcoupon.template_id
            data['activity_name'] = alidiscountcoupon.activity_name
            data['status_display'] = alidiscountcouponinfo.get_status_display()
            data['status'] = alidiscountcouponinfo.status
            data['create_time'] = alidiscountcouponinfo.gmt_distributed.strftime("%Y-%m-%d %H:%M:%S")
            data['expired_time'] = ''
            data['mobile'] = alidiscountcouponinfo.mobile
            data['out_biz_no'] = alidiscountcouponinfo.out_biz_order
            data['use_time'] = ''
            data['return_msg'] = alidiscountcouponinfo.return_msg
        else:
            data = {}
            data['voucher_id'] = alidiscountcouponinfo.voucher_id
            data['activity_id'] = alidiscountcoupon.template_id
            data['activity_name'] = alidiscountcoupon.activity_name
            data['status_display'] = alidiscountcouponinfo.get_status_display()
            data['status'] = alidiscountcouponinfo.status
            data['create_time'] = alidiscountcouponinfo.gmt_distributed.strftime("%Y-%m-%d %H:%M:%S")
            if alidiscountcouponinfo.gmt_expired:
                data['expired_time'] = alidiscountcouponinfo.gmt_expired.strftime("%Y-%m-%d %H:%M:%S")
            else:
                data['expired_time'] = ''
            data['mobile'] = alidiscountcouponinfo.mobile
            data['out_biz_no'] = alidiscountcouponinfo.out_biz_order
            if alidiscountcouponinfo.gmt_use:
                data['use_time'] = alidiscountcouponinfo.gmt_use.strftime("%Y-%m-%d %H:%M:%S")
            else:
                data['use_time'] = ''
            if alidiscountcouponinfo.gmt_active:
                data['active_time'] = alidiscountcouponinfo.gmt_use.strftime("%Y-%m-%d %H:%M:%S")
            else:
                data['active_time'] = ''
            data['return_msg'] = ''
        return Response(request_data, status=status.HTTP_200_OK)

    def ylx_distribuye(self, request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        print(ip)
        ip_white_table = APIWhiteTable.objects.filter(char=ip)
        if not ip_white_table:
            return Response({'code': 400, 'message': '非白名单内ip,请联系管理员处理'}, status=status.HTTP_200_OK)
        try:
            logger_vouchers.info(str(self.request.data))
            data = self.request.data.copy()
        except:
            return Response({'code': 400, 'message': '参数格式有误'}, status=status.HTTP_200_OK)
        sign = data.pop('sign', None)
        activity_id = data.get('activity_id', None)
        mobile = data.get('user', None)
        tel = data.get('mobile', None)
        login_id = data.get('login_id', None)
        appid = data.get('appid', None)
        openid = data.get('openid', None)
        out_biz_order = data.get('out_biz_order', None)
        if not sign:
            return Response({'code': 400, 'message': '缺少sign参数'}, status=status.HTTP_200_OK)
        if not out_biz_order:
            return Response({'code': 400, 'message': '缺少out_biz_order参数'}, status=status.HTTP_200_OK)
        if not mobile:
            return Response({'code': 400, 'message': '缺少user参数'}, status=status.HTTP_200_OK)
        if not activity_id:
            return Response({'code': 400, 'message': '缺少activity_id参数'}, status=status.HTTP_200_OK)
        if not tel:
            return Response({'code': 400, 'message': '缺少mobile参数'}, status=status.HTTP_200_OK)
        if not re.match(r'^1[3-9]\d{9}$', tel):
            return Response({'code': 400, 'message': 'mobile参数请上传手机格式'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = User.objects.get(mobile=mobile)
        except:
            return Response({'code': 400, 'message': '无效身份参数'}, status=status.HTTP_200_OK)
        key = user.authen_key
        if not key:
            return Response({'code': 400, 'message': '用户尚未开通接口权限'}, status=status.HTTP_200_OK)
        if len(out_biz_order) > 32:
            return Response({'code': 400, 'message': 'out_biz_no参数格式有误'}, status=status.HTTP_200_OK)
        params_list = sorted(data.items(), key=lambda e: e[0], reverse=False)
        params_str = "&".join(u"{}={}".format(k, v) for k, v in params_list)
        check_sign = hmac.new(bytes(key, encoding='utf-8'), bytes(params_str, encoding='utf-8'), digestmod=hashlib.sha256).digest().hex().upper()
        if sign[0] != check_sign and sign != check_sign:
            return Response({'code': 400, 'message': '签名错误'}, status=status.HTTP_200_OK)
        check_instance = AliDiscountCouponInfo.objects.filter(out_biz_order=out_biz_order)
        if check_instance:
            if user.id == 24:
                return Response({'code': 200, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
            elif user.id == 65375:
                return Response({'code': 200, 'message': '上传成功'}, status=status.HTTP_200_OK)
            else:
                return Response({'code': 400, 'message': '重复out_biz_no'}, status=status.HTTP_200_OK)
        try:
            activity = AliDiscountCoupon.objects.get(template_id=activity_id, coupon_way=5, coupon_status=1, coupon_channel__in=[1, 2])
        except:
            return Response({'code': 400, 'message': '无效活动id'}, status=status.HTTP_200_OK)
        ali_discount_coupon_api_relation = AliDiscountCouponAPIRelation.objects.filter(developer_id=user.id, alidiscountcoupon_id=activity.id)
        if not ali_discount_coupon_api_relation:
            return Response({'code': 400, 'message': '无权限派发当前活动'}, status=status.HTTP_200_OK)
        if activity.coupon_channel == 1:
            if not login_id:
                return Response({'code': 400, 'message': '缺少login_id参数'}, status=status.HTTP_200_OK)
        elif activity.coupon_channel in [2, 3]:
            appid_white_table = APIWhiteTable.objects.filter(char=appid)
            if not appid_white_table:
                return Response({'code': 400, 'message': '无效接入appid'}, status=status.HTTP_200_OK)
            if not openid:
                return Response({'code': 400, 'message': '缺少openid参数'}, status=status.HTTP_200_OK)
            if len(openid) > 32:
                return Response({'code': 400, 'message': 'openid参数格式有误'}, status=status.HTTP_200_OK)
        if activity.remain_number <= 0:
            return Response({'code': 400, 'message': '活动额度已消耗完'}, status=status.HTTP_200_OK)
        # try:
        #     channelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
        #     if channelcommonvoucher.distributed_limit_by_time == 1:
        #         week = str(datetime.datetime.now().weekday())
        #         enable_time = datetime.datetime.now().strftime('1970-01-01 %H:%M:%S')
        #         alidiscountcoupondstributedlimit = AliDiscountCouponDistributedLimit.objects.filter(ali_discount_coupon_common_voucher_id=channelcommonvoucher.id, weeks__contains=week, start_enable_time__lte=enable_time, end_enable_time__gte=enable_time)
        #         if not alidiscountcoupondstributedlimit:
        #             return Response({'code': 400, 'message': '没到活动派发时间'}, status=status.HTTP_200_OK)
        # except:
        #     pass
        # if activity.max_number_by_day:
        #     begin_time = datetime.datetime.now().strftime('%Y-%m-%d 00:00:00')
        #     end_time = datetime.datetime.now().strftime('%Y-%m-%d 23:59:59')
        #     max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, gmt_create__gte=begin_time, gmt_create__lte=end_time).count()
        #     if max_no >= activity.max_number_by_day:
        #         return Response({'code': 400, 'message': '今天的优惠券已领取完毕，请明天0点继续参与，感谢您对本活动的支持！'}, status=status.HTTP_200_OK)
        # if activity.max_number_by_user:
        #     if activity.coupon_channel == 1:
        #         max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, login_id=login_id).count()
        #         if max_no >= activity.max_number_by_user:
        #             return Response({'code': 400, 'message': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_200_OK)
        #     else:
        #         max_no = AliDiscountCouponInfo.objects.filter(alidiscountcoupon_id=activity.id, user_id=openid).count()
        #         if max_no >= activity.max_number_by_user:
        #             return Response({'code': 400, 'message': '用户参与活动次数已达上限，感谢您对本活动的支持！'}, status=status.HTTP_200_OK)
        activity_id = activity.id
        out_biz_no = f'{str(datetime.datetime.now()).replace("-", "").replace(":", "").replace(" ", "").replace(".", "")}{"%06d" % randint(0, 999999)}'
        a = 0
        with transaction.atomic():
            save_id = transaction.savepoint()
            try:
                while True:
                    if a >= 20:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '系统繁忙'}, status=status.HTTP_200_OK)
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    if activity.remain_number <= 0:
                        transaction.savepoint_rollback(save_id)
                        return Response({'code': 400, 'message': '活动额度已消耗完'}, status=status.HTTP_200_OK)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count + 1
                    activity_new_remain_number = activity_origin_remain_number - 1
                    result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(
                        send_count=activity_new_send_count,
                        remain_number=activity_new_remain_number
                    )
                    if result == 0:
                        a += 1
                        continue
                    break
                data = {
                    'alidiscountcoupon_id': activity.id,
                    'template_id': activity_id,
                    'out_biz_no': out_biz_no,
                    'gmt_distributed': datetime.datetime.now(),
                    'login_id': login_id,
                    'companyuser_id': user.id,
                    'appid': appid,
                    'user_id': openid,
                    'out_biz_order': out_biz_order,
                    'status': 0,
                    'mobile': tel,
                    'coupon_channel': activity.coupon_channel,
                    'level_id': activity.level_id
                }
                voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=data, out_biz_order=out_biz_order)
                transaction.savepoint_commit(save_id)
            except:
                transaction.savepoint_rollback(save_id)
                return Response({'code': 400, 'message': '系统繁忙'}, status=status.HTTP_200_OK)
        request_data = {}
        if activity.coupon_channel == 1:
            alipay_obj = c_AlipayOpen()
            template_id = activity.template_id
            login_id = voucherinfo.login_id
            out_biz_no = voucherinfo.out_biz_no
            response_data = json.loads(alipay_obj.vouchersend_login_id(login_id, template_id, out_biz_no))
            if response_data['code'] != '10000':
                request_data['code'] = 400
                request_data['message'] = '发券失败'
                voucherinfo.status = 14
                voucherinfo.return_msg = response_data['sub_msg']
                voucherinfo.gmt_create = datetime.datetime.now()
                voucherinfo.save()
                request_data['return_msg'] = result['sub_msg']
                request_data['out_biz_no'] = voucherinfo.out_biz_order
                request_data['create_time'] = voucherinfo.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['status_display'] = '领取失败'
                request_data['status'] = 14
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count - 1
                    activity_new_remain_number = activity_origin_remain_number + 1
                    result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                    if result1 == 0:
                        continue
                    break
            else:
                voucher_id = response_data['voucher_id']
                result = json.loads(alipay_obj.voucherquery(voucher_id))
                voucherinfo.voucher_id = voucher_id
                voucherinfo.template_id = result['template_id']
                voucherinfo.gmt_active = result['gmt_active']
                voucherinfo.gmt_expired = result['gmt_expired']
                voucherinfo.total_amount = result['total_amount']
                voucherinfo.gmt_create = result['gmt_create']
                voucherinfo.available_amount = result['available_amount']
                voucherinfo.name = result['name']
                voucherinfo.status = 1
                voucherinfo.save()
                request_data['err_code_des'] = ''
                request_data['out_biz_no'] = voucherinfo.out_biz_order
                request_data['create_time'] = voucherinfo.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['expired_time'] = result['gmt_expired']
                request_data['status_display'] = '待核销'
                request_data['status'] = 1
                request_data['total_amount'] = voucherinfo.total_amount
                request_data['voucher_id'] = voucher_id
                request_data['active_time'] = result['gmt_active']
        else:
            out_biz_no = voucherinfo.out_biz_no
            appid = voucherinfo.appid
            openid = voucherinfo.user_id
            if activity.platform_id == 13:
                distribute_channel = Channel.objects.get(id=13)
            else:
                distribute_channel = Channel.objects.get(id=9)
            data_json = {
                "stock_id": activity.template_id,
                "out_request_no": out_biz_no,
                "appid": appid,
                "stock_creator_mchid": activity.platform.mchid
            }
            response_data = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
            if 'code' in response_data:
                voucherinfo.status = 14
                voucherinfo.return_msg = response_data['message']
                voucherinfo.gmt_create = datetime.datetime.now()
                voucherinfo.save()
                request_data['return_msg'] = response_data['message']
                request_data['out_biz_no'] = voucherinfo.out_biz_order
                request_data['create_time'] = voucherinfo.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['status_display'] = '领取失败'
                request_data['status'] = 14
                while True:
                    activity = AliDiscountCoupon.objects.get(id=activity_id)
                    activity_origin_send_count = activity.send_count
                    activity_origin_remain_number = activity.remain_number
                    activity_new_send_count = activity_origin_send_count - 1
                    activity_new_remain_number = activity_origin_remain_number + 1
                    result1 = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count,remain_number=activity_new_remain_number)
                    if result1 == 0:
                        continue
                    break
            else:
                coupon_id = response_data['coupon_id']
                result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                voucherinfo.voucher_id = coupon_id
                voucherinfo.template_id = result['stock_id']
                voucherinfo.gmt_active = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
                voucherinfo.gmt_expired = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
                voucherinfo.total_amount = result['normal_coupon_information']['coupon_amount'] / 100
                voucherinfo.gmt_create = datetime.datetime.now()
                voucherinfo.available_amount = result['normal_coupon_information']['coupon_amount'] / 100
                voucherinfo.name = result['coupon_name']
                voucherinfo.status = 1
                voucherinfo.save()
                request_data['return_msg'] = ''
                request_data['out_biz_no'] = voucherinfo.out_biz_order
                request_data['create_time'] = voucherinfo.gmt_distributed.strftime('%Y-%m-%d %H:%M:%S')
                request_data['expired_time'] = result['available_end_time'].replace('T', ' ').replace('+08:00', '')
                request_data['status_display'] = '待核销'
                request_data['status'] = 1
                request_data['total_amount'] = voucherinfo.total_amount
                request_data['voucher_id'] = coupon_id
                request_data['active_time'] = result['available_begin_time'].replace('T', ' ').replace('+08:00', '')
        return Response({'code': 200, 'message': '派发成功', 'data': request_data}, status=status.HTTP_200_OK)











